package com.qiwx.pigeon.fragment.query;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.andview.refreshview.XRefreshView;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.NumberUtil;
import com.qiwx.pigeon.activity.MainActivity;
import com.qiwx.pigeon.activity.query.LayEggRecordActivity;
import com.qiwx.pigeon.adapter.query.CageAdapter;
import com.qiwx.pigeon.base.BaseMVPFragment;
import com.qiwx.pigeon.data.params.CageParam;
import com.qiwx.pigeon.data.params.QueryCageParam;
import com.qiwx.pigeon.data.vo.EggLoseBean;
import com.qiwx.pigeon.data.vo.LayEggAmountBean;
import com.qiwx.pigeon.data.vo.QueryCageBean;
import com.qiwx.pigeon.data.vo.QueryFertilizedBean;
import com.qiwx.pigeon.data.vo.CageProduceBean;
import com.qiwx.pigeon.data.vo.SummaryOther;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.fragment.ProduceFragment;
import com.qiwx.pigeon.presenter.QueryCagePresenter;
import com.qiwx.pigeon.viewinterface.IQueryCageView;
import com.qiwx.pigeon.widget.itemderection.LineItemDecoration;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import fj.dropdownmenu.lib.ion.ViewInject;
import fj.dropdownmenu.lib.ion.ViewUtils;
import fj.dropdownmenu.lib.utils.DropdownUtils;
import fj.dropdownmenu.lib.view.DropdownButton;
import fj.dropdownmenu.lib.view.DropdownColumnView;

import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_END;
import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_START;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-28 10:52
 * 鸽笼情况查询
 **/
public class QueryCageFragment extends BaseMVPFragment<IQueryCageView, QueryCagePresenter> implements IQueryCageView {

    @BindView(R.id.txt_start_date)
    TextView txtStartDate;
    @BindView(R.id.txt_end_date)
    TextView txtEndDate;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.mask)
    View mask;
    @ViewInject(R.id.drop_filter_1)
    @BindView(R.id.drop_filter_1)
    DropdownButton dropFilter1;
    @ViewInject(R.id.drop_filter_2)
    @BindView(R.id.drop_filter_2)
    DropdownButton dropFilter2;
    @ViewInject(R.id.drop_filter_3)
    @BindView(R.id.drop_filter_3)
    DropdownButton dropFilter3;
    @ViewInject(R.id.drop_filter_4)
    @BindView(R.id.drop_filter_4)
    DropdownButton dropFilter4;
    @ViewInject(R.id.drop_filter_5)
    @BindView(R.id.drop_filter_5)
    DropdownButton dropFilter5;
    @ViewInject(R.id.drop_nofertilization)
    @BindView(R.id.drop_nofertilization)
    DropdownColumnView dropdownColumnView1;
    @ViewInject(R.id.drop_deadfertilization)
    @BindView(R.id.drop_deadfertilization)
    DropdownColumnView dropdownColumnView2;
    @ViewInject(R.id.drop_badfertilization)
    @BindView(R.id.drop_badfertilization)
    DropdownColumnView dropdownColumnView3;
    @ViewInject(R.id.drop_layegg)
    @BindView(R.id.drop_layegg)
    DropdownColumnView dropdownColumnView4;
    @ViewInject(R.id.drop_fertilizationed)
    @BindView(R.id.drop_fertilizationed)
    DropdownColumnView dropdownColumnView5;
    @ViewInject(R.id.drop_filter_sort)
    @BindView(R.id.drop_filter_sort)
    DropdownButton dropFilterSort;
    @ViewInject(R.id.drop_sort)
    @BindView(R.id.drop_sort)
    DropdownColumnView dropSort;
    @BindView(R.id.txt_nodata)
    TextView txtNodata;
    @BindView(R.id.lin_nodata)
    LinearLayout linNodata;
    @BindView(R.id.xRefreshView)
    XRefreshView xRefreshView;
    int currentWh_id;//选择后鸽仓id
    CageAdapter adapter;
    List<CageProduceBean> list = new ArrayList<>();

    int offset = 0;//偏移量
    int pageSize = 20;//每页显示20条记录
    int pageNum = 1;
    //筛选
    String con_wuj = "0";//无精数
    String con_sj = "0";//死精数
    String con_fh = "0";//孵坏数
    String con_cdl = "1000000";//产蛋量
    String con_sjs = "0";//受精数
    QueryCageParam queryCageParam = new QueryCageParam();
    boolean isFresh;

    String startDate = "";
    String endDate = "";
    @BindView(R.id.lin_content)
    LinearLayout linContent;
    //当前查询wh_id，每次onresume检查 查询鸽仓id是否与当前一致，不一致则刷新数据
    int query_wh_id;//


    @Override
    public int getLayoutId() {
        return R.layout.fragment_query_cage;
    }

    @Override
    public void initAfterOnCreate() {
        super.initAfterOnCreate();
        queryCageParam.setPageSize(pageSize);
        initView();
        initFilter();
//        initSpinner();
        //loadData(true);
    }


    @Override
    public QueryCagePresenter createPresenter() {
        return new QueryCagePresenter(new WeakReference(this));
    }

    //改变排序规则
    public void changeSort(String type) {
//        switch (type) {
//            case "0"://综合不排序
//                conditionSort = "";
//                break;
//            case "1"://产蛋窝数
//                conditionSort = "order by amount desc ";
//                break;
//            case "2"://2个蛋无精
//                conditionSort = "order by wuj2 desc ";
//                break;
//            case "3"://孵坏蛋
//                conditionSort = "order by broken desc ";
//                break;
//            case "4"://死精数
//                conditionSort = "order by sij2 desc ";
//                break;
//            case "5":
//                conditionSort = "order by s2wj1,s2sj1 desc ";
//                break;
//        }
        queryCageParam.setOrder_type(NumberUtil.parseInt(type));
        loadData(true);
    }

    //改变筛选条件
    public void changeFilter(int type, String amount) {
        switch (type) {
            case 1://2个无精
                con_wuj = amount;
                queryCageParam.setCon_wuj(NumberUtil.parseInt(con_wuj));
                break;
            case 2://2个死精
                con_sj = amount;
                queryCageParam.setCon_sj(NumberUtil.parseInt(con_sj));

                break;
            case 3://孵坏
                con_fh = amount;
                queryCageParam.setCon_fh(NumberUtil.parseInt(con_fh));

                break;
            case 4://产蛋量
                con_cdl = amount;
                queryCageParam.setCon_cdl(NumberUtil.parseInt(con_cdl));

                break;
            case 5://单个受精包括 1受1死 和1受1无
                con_sjs = amount;
                queryCageParam.setCon_sjs(NumberUtil.parseInt(con_sjs));

                break;

        }
        loadData(true);
    }

    private void initFilter() {
        DropdownUtils.initFragment(getActivity(), this, view, mask);
        ViewUtils.injectFragmentViews(this, view, mask);
        //排序
        dropSort.setSingleRow(selectObj -> {
            changeSort(selectObj.getValue());
        })
                .setSingleRowList(QueryFilterData.getDataOrder(), 0)  //单列数据
                .setButton(dropFilterSort) //按钮
                .show();
        //无精蛋窝数
        dropdownColumnView1.setSingleRow(selectObj -> {
            changeFilter(1, selectObj.getValue());
        })
                .setSingleRowList(QueryFilterData.getWJData(), 0)
                .setButton(dropFilter1) //按钮
                .show();
        //死精数
        dropdownColumnView2.setSingleRow(selectObj -> {
            changeFilter(2, selectObj.getValue());

        })
                .setSingleRowList(QueryFilterData.getSJData(), 0)
                .setButton(dropFilter2) //按钮
                .show();
        dropdownColumnView3.setSingleRow(selectObj -> {
            changeFilter(3, selectObj.getValue());

        })
                .setSingleRowList(QueryFilterData.getFHData(), 0)  //单列数据
                .setButton(dropFilter3) //按钮
                .show();
        dropdownColumnView4.setSingleRow(selectObj -> {
            changeFilter(4, selectObj.getValue());
        })
                .setSingleRowList(QueryFilterData.getCDData(), 0)
                .setButton(dropFilter4) //按钮
                .show();
        dropdownColumnView5.setSingleRow(selectObj -> {
            changeFilter(5, selectObj.getValue());
        })
                .setSingleRowList(QueryFilterData.getData5(), 0)
                .setButton(dropFilter5) //按钮
                .show();

    }


    private void initView() {
        //默认查询当前日期30天之前
        long start = DateTimeUtils.addDay(new Date(), -30).getTime();
        long end = DateTimeUtils.getCurrentStamp();
        txtStartDate.setText(DateTimeUtils.timeStamp2Date(start));
        txtEndDate.setText(DateTimeUtils.timeStamp2Date(end));
        startDate = txtStartDate.getText().toString();
        endDate = txtEndDate.getText().toString();
        xRefreshView.setHideFooterWhenComplete(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                loadData(true);

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                pageNum++;
                loadData(false);
            }
        });
        adapter = new CageAdapter(R.layout.adapter_query_cage_list_item, list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerview.setLayoutManager(linearLayoutManager);
//        int space = ScreenUtils.dip2px(getActivity(), );
        recyclerview.addItemDecoration(new LineItemDecoration(1));
        recyclerview.setAdapter(adapter);
        adapter.setICageInterface((pos, status, methodId) -> {
            onAdapterClick(pos, methodId);
        });
    }

    void onAdapterClick(int pos, int methodId) {
        switch (methodId) {
            case 0:
                addEliminate(list.get(pos));
                break;
            case 1:
                checkLayEggRecord(list.get(pos));
                break;
        }

    }

    //刷新Date数据
    private void onReFreshDate() {
        startDate = txtStartDate.getText().toString();
        endDate = txtEndDate.getText().toString();
    }

    //查看鸽笼下蛋记录表
    public void checkLayEggRecord(CageProduceBean bean) {
        Intent go = new Intent(getActivity(), LayEggRecordActivity.class);
        go.putExtra("c_id", bean.getC_id());
        go.putExtra("c_number", bean.getC_number());
        startActivity(go);

    }

    //添加鸽笼到淘汰表里
    public void addEliminate(CageProduceBean bean) {
        CageParam param = new CageParam();
        param.setWh_id(bean.getWh_id());
        param.setC_id(bean.getC_id());
        param.setC_number(bean.getC_number());
        param.setEliminate_reason("应淘汰");
        mPresenter.addCageEliminate(param);
    }

    @Override
    public void onResume() {
        super.onResume();
        changeData();
    }

    public void changeData() {
        if (query_wh_id != MainActivity.wh_id) {
            loadData(true);
        }
    }

    public void loadData(boolean isFreash) {
        this.isFresh = isFreash;
        if (isFreash) {
            list.clear();
            pageNum = 1;
        }
        query_wh_id = MainActivity.wh_id;
        queryCageParam.setWh_id(query_wh_id);

        queryCageParam.setPageNum(pageNum);
        queryCageParam.setStartDate(startDate);
        queryCageParam.setEndDate(endDate);
        mPresenter.queryCageFertilizeByPage(queryCageParam);


        //loadData(isFreash, false, 0);
    }


//    private void initSpinner() {
//        spinnerWh.setPadding(ScreenUtils.dip2px(getActivity(), 7), 0, 0, 0);
//        List<WareHouseBean> list = AppContext.houses;
//        List<String> data = new ArrayList<>();
//        for (int i = 0; i < list.size(); i++) {
//            data.add(list.get(i).getNumber() + "号仓");
//        }
//        spinnerWh.attachDataSource(data);
//        spinnerWh.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
//            currentWh_id = list.get(position).getId();
//            wh_number = list.get(position).getNumber();
//            queryCageParam.setWh_id(currentWh_id);
//            loadData(true);
//
//        });
//        if (list.size() > 0) {
//            currentWh_id = list.get(0).getId();
//            wh_number = list.get(0).getNumber();
//            queryCageParam.setWh_id(currentWh_id);
//        }
//
//    }


    //根据条件查询鸽笼情况
    public void queryCages() {
        loadData(true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_START:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("car_Time_MSG"))) {
                    txtStartDate.setText(data.getStringExtra("car_Time_MSG"));
                    startDate = data.getStringExtra("car_Time_MSG");
                }
                break;
            case REQUEST_CODE_END:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("car_Time_MSG"))) {
                    txtEndDate.setText(data.getStringExtra("car_Time_MSG"));
                    endDate = data.getStringExtra("car_Time_MSG");
                }
                break;
        }
    }


    @OnClick({R.id.txt_start_date, R.id.txt_end_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_start_date:
                selectStartValiDate();
                break;
            case R.id.txt_end_date:
                selectEndValiDate(txtStartDate.getText().toString());
                break;
        }
    }

    @Override
    public void onSearchSuccess(CageProduceBean bean) {

    }

    @Override
    public void onQueryCageSuccess(PageInfo<CageProduceBean> bean) {
        list.addAll(bean.getList());
        adapter.notifyDataSetChanged();

        if (isFresh) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
            if (!bean.isHasNextPage()) {
                MyToast.showLong("没有更多数据了");
            }
        }
        if (!bean.isHasNextPage()) {
            xRefreshView.setPullLoadEnable(false);
        } else {
            xRefreshView.setPullLoadEnable(true);
        }

    }

    @Override
    public void onQueryLayEggSuccess(List<LayEggAmountBean> data) {

    }

    @Override
    public void onQueryEggLoseSuccess(List<EggLoseBean> data) {

    }

    @Override
    public void onQueryShoujSuccess(List<QueryFertilizedBean> data) {

    }

    @Override
    public void onQueryOtherSuccess(List<SummaryOther> data) {

    }

    @Override
    public void onAddCageEliminateSuccess(int type) {
        MyToast.showShort("添加到淘汰列表成功");

    }

    @Override
    public void onFailure(String error) {
        if (isFresh) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }

    }
}
